package com.jh.pattern.prototype.deepclone;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

/**
 * @author JH_Wong
 * @projectName newforward
 * @title
 * @package com.jh.pattern.prototype.deepclone
 * @description
 * @date 2019-05-30 22:59
 */
public class MonkeyKing extends Monkey implements Cloneable, Serializable {

    private JinGuBan jinGuBan;

    public MonkeyKing() {
        this.setBirthday(new Date());
        this.jinGuBan = new JinGuBan();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        try{
            // 输出
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            // 读取
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            MonkeyKing copy = (MonkeyKing) ois.readObject();
            copy.setBirthday(new Date());

            return copy;
        } catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public MonkeyKing simpleClone() {
        MonkeyKing copy = new MonkeyKing();
        copy.setHeight(this.getHeight());
        copy.setWeight(this.getWeight());
        copy.setBirthday(new Date());
        copy.setJinGuBan(this.jinGuBan);
        return copy;
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        MonkeyKing a = new MonkeyKing();

        MonkeyKing copyDeep = (MonkeyKing) a.clone();
        System.out.println("deepClone：");
        // false，readObject()方法怎样都会newInstance()一遍
        System.out.println(copyDeep.getJinGuBan() == a.getJinGuBan());

        MonkeyKing copySimple = a.simpleClone();
        System.out.println("simpleClone：");
        // true，只是值赋值过去了，引用没变还是指向同一个
        System.out.println(copySimple.getJinGuBan() == a.getJinGuBan());
    }

    public JinGuBan getJinGuBan() {
        return jinGuBan;
    }

    public void setJinGuBan(JinGuBan jinGuBan) {
        this.jinGuBan = jinGuBan;
    }
}
